#!/bin/sh

current_path=$(cd $(dirname $0) && pwd )
#echo $current_path

APP_NAME="DataCenter"
APP_DIR=$current_path

echo "APP name: "$APP_NAME
echo "APP directory: "$APP_DIR

app_pid_list="null"


kill_duplicate_app(){
	kill -9 $app_pid_list
	echo "kill -9 "$app_pid_list
}

app_run(){
	cd $APP_DIR
	killall $APP_NAME
	echo $APP_NAME" restart..."
	chmod -R 777 $APP_NAME
	export LD_LIBRARY_PATH=$current_path/lib:$LD_LIBRARY_PATH
	./$APP_NAME -DW &
}

app_duplicate_check(){
	# 1 ubuntu
	#app_pid_list=$(ps aux | grep -v 'grep' | grep -w "$APP_NAME" | awk '{print $2}')

	# 2 openwrt
	app_pid_list=$(ps w | grep -v 'grep' | grep -w "$APP_NAME" | awk '{print $1}')

	#echo "app_pid_list: "$app_pid_list
	app1=$( echo ${app_pid_list} | awk '{print $1}')
	app2=$( echo ${app_pid_list} | awk '{print $2}')
	#echo "app1 pid: "$app1
	#echo "app2 pid: "$app2

	if [ -z "$app_pid_list" ]; then
		#echo "no app running"
		app_run
	else
		if [ -n "$app2" ]; then
			#echo "kill_duplicate_app"
			kill_duplicate_app
		fi
	fi
}

while [ 1 ]; do

	app_duplicate_check
	sleep 3

done
#####
